package controller

import (
	"fmt"
	"strconv"
	"time"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/log"
	"shaw.com/entPj/ent/user"
	"shaw.com/entPj/internal/model"
	"shaw.com/entPj/pkg/config"
)

func GetAllUser(c *fiber.Ctx) error {
	client := config.GetDbinstance()
	u, err := client.User.Query().All(c.Context())
	if err != nil {
		log.Info(err.Error())
		return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("查询出现异常 %s", err.Error()))
	}

	return c.JSON(u)
}

func InsertAnUser(c *fiber.Ctx) error {
	var user model.User
	err := c.BodyParser(&user)
	if err != nil {
		return fiber.NewError(fiber.StatusBadRequest, "错误的请求体")
	}

	client := config.GetDbinstance()

	// ent 不支持直接保存整个实体类（如 user.Save()），只能通过 Create/Update builder 设置字段
	_, err = client.User.
		Create().
		SetUsername(user.Username).
		SetPassword(user.Password).
		SetEmail(user.Email).
		SetCreatedAt(time.Now()).
		Save(c.Context())
	if err != nil {
		log.Info(err.Error())
		return fiber.NewError(fiber.StatusInternalServerError, fmt.Sprintf("插入用户失败: %s", err.Error()))
	}

	return c.SendString("插入成功！")
}

func InsertAnPet(c *fiber.Ctx) error {
	userIDStr := c.Query("user_id")
	userID, err := strconv.Atoi(userIDStr)
	if err != nil {
		return fiber.NewError(fiber.StatusBadRequest, "无效的 user_id")
	}

	p := model.Pet{}
	err = c.BodyParser(&p)
	if err != nil {
		return fiber.NewError(fiber.StatusBadRequest, "无效的 body")
	}

	client := config.GetDbinstance()

	user, err := client.User.Query().
		Where(user.ID(userID)).
		Only(c.Context())
	if err != nil {
		log.Error(err.Error())
		return fiber.NewError(fiber.StatusInternalServerError, "获取用户信息失败")
	}

	t := time.Now()

	// 这里的user需要ent.User 实体，需要从数据库中进行查询
	_, err = client.Pet.Create().
		SetName(p.Name).
		SetAge(p.Age).
		SetType(p.Type).
		SetOwner(user).
		SetNillableCreatedAt(&t).
		Save(c.Context())
	if err != nil {
		log.Fatalf("failed creating pet: %v", err)
	}

	return c.SendString("插入成功")
}

func FindUserPets(c *fiber.Ctx) error {
	str := c.Query("user_id")
	id, err := strconv.Atoi(str)
	if err != nil {
		return fiber.NewError(fiber.StatusBadRequest, "无效的 user_id")
	}

	client := config.GetDbinstance()
	u, err := client.User.Query().
		Where(user.ID(id)).
		WithPets().
		Only(c.Context())
	if err != nil {
		return fiber.NewError(fiber.StatusInternalServerError, "查询失败")
	}
	return c.JSON(u)
}
